$(function () {
    var opflag = $.getQueryString("opflag") || globalData.flowRunPrcs.opFlag;
    var runId = $.getQueryString("runId") || '';
    var flowId = $.getQueryString("flowId");

    // 判断父子流程跳转显示
    $.ajax({
        url: '/workflow/work/prentAndSonFlow',
        type: 'get',
        data: {'runId': runId},
        dataType: 'json',
        async: false,
        success: function (json) {
            if (json.flag) {
                var str = [];
                var str2 = '';
                // 父流程
                if (json.object) {
                    str.push('<li class="parent_child_item" title="' + json.object.runName + '" runid="' + json.object.runId + '" flowid="' + json.object.flowId + '">' + json.object.runName + '</li>')
                    str2 += '<tr><td>父流程</td><td><a class="parent_child_item" style="color:#1687cb;text-decoration: underline;cursor: pointer;" flowId="' + json.object.flowId + '" runId="' + json.object.runId + '">' + json.object.runName + '</a></td></tr>'
                    // 获取父流程关联流程数据
                    $.get('/flowRun/findrelationRunIds', {runId: json.object.runId}, function (res) {
                        var pConnectStr = ''
                        if (res.flag) {
                            if (res.obj.length > 0) {
                                res.obj.forEach(function (item) {
                                    pConnectStr += '<tr><td>关联流程</td><td><a style="color: #1687cb;text-decoration: underline;" class="open_flow_work" title="' + item.runName + '" runId="' + item.runId + '" flowId="' + item.flowId + '" href="javascript:;">' + item.runName + '</a></td></tr>'
                                });
                            }
                        }
                        $('#relevantProcessesTbody').append(pConnectStr);
                    });
                }
                // 子流程
                if (json.obj.length != 0) {
                    for (var i = 0; i < json.obj.length; i++) {
                        str.push('<li class="parent_child_item" title="' + json.obj[i].runName + '" runid="' + json.obj[i].runId + '" flowid="' + json.obj[i].flowId + '">' + json.obj[i].runName + '</li>')
                        str2 += '<tr><td>子流程</td><td><a class="parent_child_item" style="color:#1687cb;text-decoration: underline;cursor: pointer;" flowId="' + json.obj[i].flowId + '" runId="' + json.obj[i].runId + '">' + json.obj[i].runName + '</a></td></tr>'
                    }
                }
                if (str.length > 0) {
                    $('#parentOrChildBtn').show()
                    $('#parentOrChildList').css('top', -(25 + (28 * str.length)) + 'px')
                    $('#parentOrChildList').html(str.join(''))
                    $('#relevantProcessesTbody').append(str2)
                    $('#relevantProcesses').show()
                }
            }
        }
    });

    // 获取查阅情况
    $.get('/ToBeReadController/queryFileIsRead', {
        'runId': $.getQueryString('runId'),
        'prcsId': $.getQueryString('prcsId'),
        'flowPrcs': $.getQueryString('flowStep')
    }, function (res) {
        if (res.flag) {
            var str = '';
            if (res.data && res.data.length > 0) {
                var data = res.data;
                var readedUser = []
                var unreadUserStr = []
                for (var i = 0; i < data.length; i++) {
                    if (data[i].readFlag == 1) {
                        readedUser.push(data[i])
                    } else {
                        unreadUserStr.push(data[i].userName)
                    }
                }

                if (readedUser.length > 0) {
                    for (var i = 0; i < readedUser.length; i++) {
                        if (i == 0) {
                            str += '<tr><td>' + readedUser[i].userName + '</td><td>' + readedUser[i].readDate + '</td><td style="border-left: 1px solid #ddd;" rowspan="' + readedUser.length + '">' + unreadUserStr.join(',') + '</td></tr>';
                        } else {
                            str += '<tr><td>' + readedUser[i].userName + '</td><td>' + readedUser[i].readDate + '</td></tr>';
                        }
                    }
                } else {
                    str = '<tr><td></td><td></td><td style="border-left: 1px solid #ddd;">' + unreadUserStr.join(',') + '</td></tr>';
                }

                $('#readDetailTbody').append(str);
                $('#readDetail').show();
            }
        }
    });

    /********************添加关联工作流程 START*************************/
    if (globalData.flowProcesses) {
        if (globalData.flowProcesses.relationWorkYn == '1') {
            $('.add_connect_work').show();
        }
    }

    // 点击关联流程
    $('.add_connect_work').on('click', function () {
        layer.open({
            type: 1,
            title: '<span style="color: #fff;">添加关联工作</span>',
            area: ['820px', '500px'],
            content: '<div class="connect_work_modal" style="padding: 10px;height: 100%;box-sizing: border-box;">' +
                '<div class="modal_head" style="margin-bottom: 10px;">' +
                '<label style="display:inline-block;margin-right: 10px;">流程名称:' +
                '<div style="display: inline-block; position: relative;margin-left: 5px;"><input type="text" class="cw_flowid"><button id="list"><img src="/img/workflow/work/xiala.png" alt=""></button>' +
                '<ul class="sel"></ul>' +
                '</div>' +
                '</label>' +
                '<label style="display:inline-block;margin-right: 10px;">流水号:<input type="text" style="margin-left: 5px;" class="cw_runid"></label>' +
                '<label style="display:inline-block;margin-right: 10px;">工作名称/文号:<input type="text" style="margin-left: 5px;" class="cw_runname"></label>' +
                '<button class="layui-btn layui-btn-sm layui-btn-normal" onclick="searchConnectWork(this)">查询</button>' +
                '</div>' +
                '<div class="modal_content" style="padding-bottom: 10px;">' +
                '<table style="width: 100%; margin: 0; text-align: center; border-color: #fff;" border="1">' +
                '<thead><th style="padding: 5px;text-align: left;">流水号</th><th style="width: 60%;padding: 5px;text-align: left;">名称/文号</th><th style="padding: 5px;">操作</th></thead>' +
                '<tbody id="connectTable"></tbody>' +
                '</table>' +
                '</div>' +
                '</div>',
            success: function () {
                // 获取可关联的流程
                $.get('/flowRun/findFLow', function (res) {
                    if (res.flag) {
                        var str = '';
                        if (res.obj.length > 0) {
                            res.obj.forEach(function (item) {
                                str += '<tr><td style="padding: 5px;text-align: left;">' + item['runId'] + '</td><td style="width: 60%;padding: 5px;text-align: left;"><a style="cursor: pointer;text-decoration: underline;" class="open_flow_work" flowid="' + item['flowId'] + '" runid="' + item['runId'] + '">' + item['runName'] + '</a></td><td style="padding: 5px;"><a relationrunid="' + item['runId'] + '" runname="' + item['runName'] + '" href="javascript:;" class="add_connect_btn" style="color: blue;">添加</a></td></tr>'
                            });
                        }
                        $('#connectTable').html(str);
                    }
                });

                $.get('/flow/selOneToAllType', function (res) {
                    var data = res.datas;

                    if (res.flag) {
                        $.each(data, function (i, item) {
                            $('.sel').append("<li class='ones' style='font-weight:bold;font-size:14px;' id=" + item.sortId + "><img src='../../img/data_points.png' style='margin-right: 5px; margin-top: -2px;' alt=''>" + item.sortName + "<li>");
                            $.each(item.flowTypeModels, function (j, v) {
                                $('.sel').append("<li style='padding-left:10px;cursor:pointer' class='canchoose' value=" + v.flowId + ">" + v.flowName + "<li>");
                            })
                            buildNode(1, item.childs);
                        });
                    }
                });
            },
            cancel: function () {
                $('.cw_runid').val('');
                $('.cw_flowid').attr('dataType', '');
                $('.cw_flowid').val('');
                $('.cw_runname').val('');
            }
        })
    });

    $(document).click(function () {
        $('.sel').hide()
    });

    $(document).on('click', '#list', function (e) {
        e.stopPropagation()
        if ($('.sel').css('display') != 'none') {
            $('.sel').hide()
        } else {
            $('.sel').show()
        }
    });

    $(document).on('click', '.sel li', function (e) {
        e.stopPropagation()
        if ($(this).attr('value')) {
            $('.cw_flowid', $('.connect_work_modal')).val($(this).html());
            $('.cw_flowid', $('.connect_work_modal')).attr('dataType', $(this).attr('value'));
            $('.sel').hide()
        } else {
            $('.sel').show()
        }
    });

    $(document).on('keyup', '.cw_flowid', function () {
        $('.sel').show()
        var val = $(this).val()
        $('.sel li').each(function (i, v) {
            if (v.innerHTML.indexOf(val) > -1) {
                $(v).show();
                $(v).parent().show()
            } else {
                $(v).hide();
            }
        })

    });
    // 添加关联流程
    $(document).on('click', '.add_connect_btn', function () {
        var relationRunId = $(this).attr('relationrunid');
        var relationRunName = $(this).attr('runname');
        $.post('/flowRun/saveRelationRunIds', {flag: 1, runId: runId, RelationRunId: relationRunId}, function (res) {
            if (res.flag) {
                initConnectTable(runId, false);
                $('.noData1').hide();
                layer.msg('添加关联成功');
                $('.cw_runid').val('');
                $('.cw_flowid').attr('dataType', '');
                $('.cw_flowid').val('');
                $('.cw_runname').val('');
                layer.closeAll();
            }
        });
    });
    // 删除关联流程
    $(document).on('click', '.del_connect_btn', function () {
        var relationRunId = $(this).attr('relationrunid');
        var index = layer.confirm('确定删除本条关联工作？', {
            btn: ['确定', '取消']
        }, function () {
            $.post('/flowRun/saveRelationRunIds', {
                flag: 2,
                runId: runId,
                RelationRunId: relationRunId
            }, function (res) {
                if (res.flag) {
                    initConnectTable(runId, false);
                    layer.close(index);
                }
            });
        });
    });
    // 查看关联流程详情
    $(document).on('click', '.open_flow_work', function () {
        var flowId = $(this).attr('flowid');
        var runId = $(this).attr('runid');
        $.popWindow('/workflow/work/workformPreView?flowId=' + flowId + '&flowStep=&prcsId=&runId=' + runId);
    });

    initConnectTable(runId);

    /********************添加关联工作流程 END*************************/

    /***********************关联操作(分发、补发、交办、集团发文) start**************************/

    // 全选单位
    $('.selectall').on('click', function () {
        $('.select_dept_list').empty();
        var $liItems = $('.dept_list').find('li');
        $liItems.each(function () {
            var exchangeid = 'exchangeid' + $(this).data('exchangeid');
            var $item = $(this).clone()
            $item.attr('id', exchangeid)
            $('.select_dept_list').append($item)
        })
    });
    // 点击选择单位
    $('.left').on('click', '.exchange_item', function () {
        var exchangeid = 'exchangeid' + $(this).data('exchangeid');
        var $item = $(this).clone()
        $item.attr('id', exchangeid)
        var $sitem = $('#' + exchangeid, $('.right'));
        if ($sitem.length == 0) {
            $('.select_dept_list').append($item)
        }
    });
    // 取消选择单位
    $('.right').on('click', '.exchange_item', function () {
        $(this).remove();
    });
    // 清空选择
    $('.cancelall').on('click', function () {
        $('.select_dept_list').empty();
    });

    // 查看会签详情
    layui.use(['table', 'layer', 'form', 'upload'], function () {
        var table = layui.table,
            layer = layui.layer,
            form = layui.form,
            upload = layui.upload;

        // 公文操作
        $('#foot_rig').on('click', '.opt_btn', function () {
            var btnType = $(this).data('type');
            var savePath = '';

            $.ajax({
                url: '/operation/selFlowOperationById',
                type: 'GET',
                data: {opId: btnType},
                async: false,
                success: function (res) {
                    if (res.flag) {
                        savePath = '/' + res.object.useFunc;
                    }
                }
            });

            if (btnType == 8) {
                saveFlowData(function (data) {
                    if (data.flag) {
                        layer.open({
                            title: '<span style="color: #fff;">工作交办</span>',
                            type: 1,
                            area: ['600px', '370px'],
                            content: $('#work'),
                            btn: ['确定', '取消'],
                            success: function () {
                                // if (globalData.feedback == 0) {
                                //     $("#yesr").attr("checked", true)
                                //     $("#nor").attr("disabled", false)
                                // }
                                // if (globalData.feedback == 1) {
                                //     $("#yesr").attr("checked", false)
                                //     $("#nor").attr("checked", "checked")
                                // }

                                form.val("workForm", {
                                    'smstype': '5'
                                });
                            }
                            , yes: function () {
                                var neirong = '', // $('#neirong').val().trim(),
                                    flowId = $.GetRequest().flowId,
                                    runId = $.GetRequest().runId,
                                    thisrunName = $('.num').attr('thisrunName') || '',
                                    prcsId = $.GetRequest().flowStep || '',
                                    tableName = $.GetRequest().tableName || '',
                                    viewUser = $('#viewUserName').attr('user_id') || '',
                                    jingbanUser = $('#chargePerson').attr('user_id') || '',
                                    tipMsg = '您有新的公文需要办理，流水号：' + runId + '，工作名称/文号：' + globalData.flowRun.runName,
                                    smsType1 = '',
                                    attachmentId = '',
                                    attachmentName = '';

                                // if (neirong == '') {
                                //     layer.msg('请选择填写交办内容！', {icon: 2});
                                //     return false;
                                // }

                                if (jingbanUser == '') {
                                    layer.msg('请选择办理人！', {icon: 2});
                                    return false;
                                }

                                var $smsType1 = $('input[name="smstype"]:checkbox:checked', $('#work'));
                                $smsType1.each(function () {
                                    smsType1 += $(this).val() + ',';
                                });

                                var $attachments = $('#demo2').find('input[type="hidden"]');
                                $attachments.each(function () {
                                    attachmentId += $(this).val() + ',';
                                    attachmentName += $(this).data('attachname') + ',';
                                });

                                $.ajax({
                                    type: 'post',
                                    url: '/flowAssign/saveWork',
                                    dataType: 'json',
                                    data: {
                                        assignTask: neirong,
                                        flowId: flowId,
                                        runId: runId,
                                        prcsId: prcsId,
                                        thisrunName: thisrunName,
                                        tableName: tableName,
                                        jingbanUser: jingbanUser,
                                        viewUser: viewUser + ',',
                                        prcsflag: 1,
                                        prcsId: globalData.flowRunPrcs.prcsId,
                                        currentPrcsId: globalData.flowProcesses.prcsId,
                                        flowPrcs: globalData.flowPrcs,
                                        signYn: globalData.feedback,
                                        prcsName: globalData.prcsName,
                                        attachmentId: attachmentId,
                                        attachmentName: attachmentName,
                                        smsType: smsType1,
                                        smsContent: tipMsg,
                                        topFlag: globalData.flowRunPrcs.topFlag,
                                        parent: globalData.flowRunPrcs.parent
                                    },
                                    success: function (res) {
                                        // tableIns.reload();
                                        // // 清空内容
                                        // $('#neirong').val('');
                                        // // 清空交办人
                                        // $('#chargePerson').get(0).setAttribute('user_id', '');
                                        // $('#chargePerson').val('');
                                        // // 清空附件信息
                                        // $('#demo2').empty();
                                        // layer.closeAll();
                                        // window.close();
                                        $.layerMsg({content: '交办成功', icon: 1}, function () {
                                            setTimeout(function () {
                                                window.close();
                                                if (parent.opener.openRold) {
                                                    parent.opener.openRold()
                                                }
                                            }, 100);
                                        });
                                    }
                                });
                            },
                            btn2: function () {
                                // 清空内容
                                $('#neirong').val('');
                                // 清空交办人
                                $('#chargePerson').get(0).setAttribute('user_id', '');
                                $('#chargePerson').val('');
                                // 清空附件信息
                                $('#demo2').empty();
                                layer.closeAll();
                            },
                            cancel: function () {
                                // 清空内容
                                $('#neirong').val('');
                                // 清空交办人
                                $('#chargePerson').get(0).setAttribute('user_id', '');
                                $('#chargePerson').val('');
                                // 清空附件信息
                                $('#demo2').empty();
                                layer.closeAll();
                            }
                        });
                    } else {
                        $.layerMsg({content: '保存失败！', icon: 2}, function () {

                        });
                    }
                })
            } else if (btnType == 1 || btnType == 2 || btnType == 9 || btnType == 10) {
                saveFlowData(function (data) {
                    if (data.flag) {
                        var getPath = '';
                        var modalTitle = '';
                        var getData = {unitType: '', ouType: '', useFlag: false};

                        var unitPath = 'DOC_EXCHANGE_UNIT_TYPE';
                        if (btnType == 1) { // 公文分发
                            getPath = '/documentExchangeSet/selectByDocumentPriv';
                            modalTitle = '选择分发单位';
                        } else if (btnType == 2) { // 公文补发
                            getPath = '/documentExchangeReceive/reinsertDocumentReceive';
                            modalTitle = '选择补发单位';
                            getData.fromRunId = runId;
                        } else if (btnType == 9) { // 集团系统发文
                            getPath = '/DocumentExchangeOutUnit/query';
                            modalTitle = '往集团系统发文';
                            unitPath = 'DOCUMENT_EXCHANGE_OUTUNIT'
                        } else if (btnType == 10) { // 联网公文补发
                            getPath = '/DocumentExchangeOutUnit/query';
                            modalTitle = '联网公文补发';
                            unitPath = 'DOCUMENT_EXCHANGE_OUTUNIT'
                        }

                        var layerIndex = layer.open({
                            title: '<span style="color: #fff;">'+modalTitle+'</span>',
                            type: 1,
                            area: ['600px', '500px'],
                            content: $('#one'),
                            btn: ['确定', '取消'],
                            success: function () {
                                // 获取附件
                                $.ajax({
                                    type: "get",
                                    url: "findworkUpload",
                                    dataType: 'JSON',
                                    data: {
                                        runId: runId
                                    },
                                    success: function (obj) {
                                        var fstr = '';
                                        if (obj.flag) {
                                            obj.obj.forEach(function (v, i) {
                                                var attachmentId = v.aid + '@' + v.ym + '_' + v.attachId;
                                                var attachmentName = v.attachName;
                                                fstr += '<li style="line-height:26px;"><input type="checkbox" name="check_file" class="check_file" style="margin: 0 5px 0 0;" data-attachmentid="' + attachmentId + '" data-attachmentname="' + attachmentName + '">' + attachmentName + '</li>'
                                            });
                                        }
                                        $('.file_list').html(fstr);
                                    }
                                });

                                $.get(getPath, getData, function (res) {
                                    if (res.flag) {
                                        var str = '';
                                        if (btnType == 9 || btnType == 10) {
                                            res.obj.forEach(function (item) {
                                                str += '<li class="exchange_item" title="' + item.ounitFullName + '" data-exchangeid="' + item.ouId + '">' + item.ounitFullName + '</li>';
                                            });
                                        } else {
                                            var formUnit = ''
                                            res.obj.forEach(function (item) {
                                                formUnit += '<option value="' + item.exchangeId + '">' + item.fromUnit + '</option>';
                                            });
                                            $('.form_unit').html(formUnit);
                                            form.render();
                                            res.object.obj.forEach(function (item) {
                                                str += '<li class="exchange_item" title="' + item.receiveUnit + '" data-exchangeid="' + item.exchangeId + '">' + item.receiveUnit + '</li>';
                                            })
                                        }
                                        $('.dept_list').html(str);
                                    }
                                });

                                $.get('/documentExchangeSet/selectByType?SysCode=' + unitPath, function (res) {
                                    $('.unit_type').empty();
                                    $('.unit_type').append($('<option value=" ">全部单位类型</option>'));
                                    if (res.flag && res.obj.length > 0) {
                                        res.obj.forEach(function (item) {
                                            var opt = '<option value="' + item.codeNo + '">' + item.codeName + '</option>';
                                            $('.unit_type').append($(opt));
                                        });
                                        form.render();
                                    }
                                });

                                if (btnType == 9 || btnType == 10) {
                                    $('.form_unit_item').hide();
                                    $('.remark_box').show();
                                    $('#remark').val('');
                                } else {
                                    $('.form_unit_item').show();
                                    $('.remark_box').hide();
                                }
                            },
                            yes: function () {
                                var loadingIndex = layer.load();
                                var $checkFile = $('.check_file:checkbox:checked');
                                var attachmentId = '';
                                var attachmentName = '';
                                if ($checkFile.length > 0) {
                                    $checkFile.each(function () {
                                        attachmentId += $(this).data('attachmentid') + ',';
                                        attachmentName += $(this).data('attachmentname') + '*';
                                    });
                                }
                                var exchangeIds = '';
                                var $selectlis = $('.right').find('li');
                                if ($selectlis.length > 0) {
                                    $selectlis.each(function () {
                                        exchangeIds += $(this).data('exchangeid') + ','
                                    });
                                }

                                if (btnType == 1 || btnType == 2) {
                                    var docNo = $('input[name="DATA_11"]').val();
                                    var title = $('input[name="DATA_10"]').val();
                                    var data = {
                                        exchangeIds: exchangeIds,
                                        docTitle: title,
                                        fromUnit: $('.form_unit').val(),
                                        docNo: docNo,
                                        fromRunId: runId,
                                        attachmentId: attachmentId,
                                        attachmentName: attachmentName
                                    }

                                    $.post(savePath, data, function (res) {
                                        layer.close(loadingIndex);
                                        if (res.flag) {
                                            if (btnType == 1) {
                                                layer.msg('分发成功', {icon: 1})
                                            } else if (btnType == 2) {
                                                layer.msg('补发成功', {icon: 1})
                                            }
                                            $('.dept_list').empty();
                                            $('.select_dept_list').empty();
                                            $('.file_list').empty();
                                            layer.close(layerIndex);
                                        } else {
                                            if (btnType == 1) {
                                                if (res.msg == "") {
                                                    layer.msg('分发失败', {icon: 2})
                                                } else {
                                                    layer.msg(res.msg, {icon: 2})
                                                }
                                            } else if (btnType == 2) {
                                                if (res.msg == "") {
                                                    layer.msg('补发失败', {icon: 2})
                                                } else {
                                                    layer.msg(res.msg, {icon: 2})
                                                }
                                            }
                                        }
                                    });
                                } else if (btnType == 9 || btnType == 10) {
                                    var data = {
                                        ouIds: exchangeIds,
                                        AttachmentIds: attachmentId,
                                        AttachmentNames: attachmentName,
                                        runId: runId,
                                        remark: $('#remark').val() || ''
                                    }

                                    $.post(savePath, data, function (res) {
                                        layer.close(loadingIndex);
                                        if (res.flag) {
                                            layer.msg(res.msg, {icon: 1});
                                            $('.dept_list').empty();
                                            $('.select_dept_list').empty();
                                            $('.file_list').empty();
                                            layer.close(layerIndex);
                                        } else {
                                            layer.msg('分发失败', {icon: 2});
                                        }
                                    });
                                }
                            },
                            btn2: function () {
                                $('.dept_list').empty();
                                $('.select_dept_list').empty();
                            },
                            cancel: function () {
                                $('.dept_list').empty();
                                $('.select_dept_list').empty();
                            }
                        });

                        form.on('select(searchSelects)', function (data) {
                            var str = '';
                            if (btnType == 9 || btnType == 10) {
                                $.get(getPath, {ouType: data.value, useFlag: false}, function (res) {
                                    if (res.flag) {
                                        res.obj.forEach(function (item) {
                                            str += '<li class="exchange_item" title="' + item.ounitFullName + '" data-exchangeid="' + item.ouId + '">' + item.ounitFullName + '</li>';
                                        });
                                    }
                                    $('.dept_list').html(str);
                                });
                            } else {
                                getData.unitType = data.value;
                                $.get(getPath, getData, function (res) {
                                    if (res.flag) {
                                        res.object.obj.forEach(function (item) {
                                            str += '<li class="exchange_item" title="' + item.receiveUnit + '" data-exchangeid="' + item.exchangeId + '">' + item.receiveUnit + '</li>';
                                        })
                                    }
                                    $('.dept_list').html(str);
                                });
                            }
                        });
                    } else {
                        $.layerMsg({content: '保存失败！', icon: 2}, function () {

                        });
                    }
                });

            } else if (btnType == 13) {
                saveFlowData(function (data) {
                    var url = '/workflow/work/workformPreView?' + location.href.split('workform?')[1] + '&type=notice' + '&btnType=' + btnType;
                    window.open(url);
                });
            } else if (btnType == 14) {
                saveFlowData(function (data) {
                    $.post(savePath, {id: globalData.flowRunPrcs.id, flag: 0}, function (res) {
                        if (res.flag) {
                            window.close();
                            if (parent.opener.openRold) {
                                parent.opener.openRold();
                            }
                        }
                    });
                });
            } else if (btnType == 16) {
                $.post(savePath, {
                    runId: globalData.flowRunPrcs.runId,
                    prcsId: globalData.flowRunPrcs.prcsId
                }, function (res) {
                    if (res.flag) {
                        layer.msg('退回成功！', {icon: 1}, function () {
                            window.close();

                            if (parent.opener.openRold) {
                                parent.opener.openRold();
                            }
                        });
                    } else {
                        layer.msg('退回失败！', {icon: 2});
                    }
                });
            }
        });

        //工作交办-附件上传
        upload.render({
            elem: '#test3'
            , url: '/flowAssign/workUpload?module=flowassign' //上传接口
            , accept: 'file' //普通文件
            , done: function (res) {
                layer.msg('上传成功');
                var data = res.obj[0];

                var fileExtension = data.attachName.substring(data.attachName.lastIndexOf(".") + 1, data.attachName.length);//截取附件文件后缀
                var attName = encodeURI(data.attachName).replace(/\+/g, "%2b").replace(/\@/g, "%40").replace(/\#/g, "%23").replace(/\&/g, "%26").replace(/\//g, "%2F").replace(/\?/g, "%3F").replace(/\￥/g, "%ef%bf%a5").replace(/\$/g, "%24").replace(/\！/g, "%ef%bc%81").replace(/\（/g, "%ef%bc%88").replace(/\）/g, "%ef%bc%89").replace(/\…/g, "%e2%80%a6%e2%80%a6");
                var fileExtensionName = attName.substring(0, attName.lastIndexOf("."));
                var deUrl = data.attUrl.split('&ATTACHMENT_NAME=')[0] + "&ATTACHMENT_NAME=" + fileExtensionName + "." + fileExtension + "&FILESIZE=" + data.size;
                var str = '<div class="dech" deUrl="' + deUrl + '"><a href="/download?' + encodeURI(deUrl) + '" NAME="' + data.attachName + '*"><img style="margin-top: -3px; margin-right: 3px;" src="/img/attachment_icon.png"/>' + data.attachName + '</a><img class="deImgs" style="margin-left:5px;cursor: pointer;" src="/img/file/icon_deletecha_03.png"/><input type="hidden" data-attachname="' + data.attachName + '" class="inHidden" value="' + data.aid + '@' + data.ym + '_' + data.attachId + ',"></div>';

                $('#demo2').append(str);
            }
        });

        //工作办理-附件上传
        upload.render({
            elem: '#test4'
            , url: '/flowAssign/workUpload?module=flowassign' //上传接口
            , accept: 'file' //普通文件
            , done: function (res) {
                layer.msg('上传成功');
                var data = res.obj[0];
                var data = res.obj[0];
                var fileExtension = data.attachName.substring(data.attachName.lastIndexOf(".") + 1, data.attachName.length);//截取附件文件后缀
                var attName = encodeURI(data.attachName).replace(/\+/g, "%2b").replace(/\@/g, "%40").replace(/\#/g, "%23").replace(/\&/g, "%26").replace(/\//g, "%2F").replace(/\?/g, "%3F").replace(/\￥/g, "%ef%bf%a5").replace(/\$/g, "%24").replace(/\！/g, "%ef%bc%81").replace(/\（/g, "%ef%bc%88").replace(/\）/g, "%ef%bc%89").replace(/\…/g, "%e2%80%a6%e2%80%a6");
                var fileExtensionName = attName.substring(0, attName.lastIndexOf("."));
                var deUrl = data.attUrl.split('&ATTACHMENT_NAME=')[0] + "&ATTACHMENT_NAME=" + fileExtensionName + "." + fileExtension + "&FILESIZE=" + data.size;
                var str = '<div class="dech" deUrl="' + deUrl + '"><a href="/download?' + encodeURI(deUrl) + '" NAME="' + data.attachName + '*"><img style="margin-top: -3px; margin-right: 3px;" src="/img/attachment_icon.png"/>' + data.attachName + '</a><img class="deImgs" style="margin-left:5px;cursor: pointer;" src="/img/file/icon_deletecha_03.png"/><input type="hidden" data-attachname="' + data.attachName + '" class="inHidden" value="' + data.aid + '@' + data.ym + '_' + data.attachId + ',"></div>';

                $('#demo3').append(str);
            }
        });

        // 工作办理、工作交办-删除附件
        $(document).on('click', '.deImgs', function () {
            var _this = this;
            var attUrl = $(this).parents('.dech').attr('deUrl');
            $.ajax({
                type: 'get',
                url: '/delete?' + attUrl,
                dataType: 'json',
                success: function (res) {

                    if (res.flag == true) {
                        $.layerMsg({content: '删除成功', icon: 1});
                        $(_this).parent().remove();
                    } else {
                        $.layerMsg({content: '删除失败', icon: 2});
                    }
                }
            })
        });

        // 交办详情-附件查阅
        $(document).on('click', '.yulan', function () {
            var url = $(this).attr('data-url');
            pdurl($.UrlGetRequest('?' + url), url);
        });
        $(document).on('click', '.chayue', function () {
            var url = $(this).attr('data-url');
            pdurl($.UrlGetRequest('?' + url), url);
        });

        var tableIns = null;
        initAssignmentTable();

        //监听-交办详情-表格-工具条
        table.on('tool(assignmenttable)', function (obj) {
            var tData = obj.data;
            var layEvent = obj.event;

            if (layEvent === '1') { // 工作办理
                // 经办人办理
                if (!!$('#foot_rig').is(':hidden')) {
                    var loadingIndex = layer.load();
                    saveFormSign(loadingIndex, function () {
                        layer.open({
                            title: '<span style="color: #fff;">工作办理</span>',
                            type: 1,
                            area: ['600px', '370px'],
                            content: $('#workDone'),
                            btn: ['确定', '取消']
                            , yes: function () {
                                var neirong1 = $("#neirong1").val();
                                var runId = $.GetRequest().runId;
                                var flowId = workForm.option.flowRun.flowId;
                                var tipMsg = '您有新的公文需要办理，流水号：' + globalData.flowRun.runId + '，工作名称/文号：' + globalData.flowRun.runName;
                                var tableName = $.getQueryString("tableName") || '';
                                var tabId = $.getQueryString("tabId") || '';
                                var smsType = '';
                                var attachmentId = '';
                                var attachmentName = '';
                                var $smsType = $('input[name="smstype"]:checkbox:checked', $('#workDone'));
                                $smsType.each(function () {
                                    smsType += $(this).val() + ',';
                                });
                                var $attachments = $('#demo3').find('input[type="hidden"]');
                                $attachments.each(function () {
                                    attachmentId += $(this).val();
                                    attachmentName += $(this).data('attachname') + ',';
                                });

                                if (!neirong1) {
                                    layer.msg('请输入办理汇报！', {icon: 2});
                                    return false;
                                }

                                $.ajax({
                                    type: 'post',
                                    url: '/flowAssign/update',
                                    dataType: 'json',
                                    data: {
                                        taskFeedback: neirong1,
                                        flowId: flowId,
                                        smsType: smsType,
                                        smsContent: tipMsg,
                                        runId: runId,
                                        prcsId: globalData.flowRunPrcs.prcsId,
                                        currentPrcsId: globalData.flowProcesses.prcsId,
                                        fdAttachmentName: attachmentName,
                                        fdAttachmentID: attachmentId,
                                        assignId: tData.assignId,
                                        id: globalData.flowRunPrcs.id,
                                        tableName: tableName,
                                        tabId: tabId,
                                        runName: globalData.flowRun.runName,
                                    },
                                    success: function (res) {
                                        if (res.flag) {
                                            $.layerMsg({content: '办理成功', icon: 1}, function () {
                                                setTimeout(function () {
                                                    window.close();
                                                    if (parent.opener.openRold) {
                                                        parent.opener.openRold()
                                                    }
                                                }, 100);
                                            });
                                        } else {
                                            layer.msg('办理失败', {icon: 2});
                                        }
                                    }
                                })
                            },
                            btn2: function () {
                                layer.closeAll();
                                $('#neirong1').val('');
                                $('#demo3').empty();
                            },
                            cancel: function () {
                                layer.closeAll();
                                $('#neirong1').val('');
                                $('#demo3').empty();
                            }
                        });
                    });
                } else { // 主办人办理
                    saveFlowData(function (data) {
                        if (data.flag) {
                            layer.open({
                                title: '<span style="color: #fff;">工作办理</span>',
                                type: 1,
                                area: ['600px', '370px'],
                                content: $('#workDone'),
                                btn: ['确定', '取消']
                                , yes: function () {
                                    var neirong1 = $("#neirong1").val();
                                    var runId = $.GetRequest().runId;
                                    var flowId = workForm.option.flowRun.flowId;
                                    var tipMsg = '您有新的公文需要办理，流水号：' + globalData.flowRun.runId + '，工作名称/文号：' + globalData.flowRun.runName;
                                    var tableName = $.getQueryString("tableName") || '';
                                    var tabId = $.getQueryString("tabId") || '';
                                    var smsType = '';
                                    var attachmentId = '';
                                    var attachmentName = '';
                                    var $smsType = $('input[name="smstype"]:checkbox:checked', $('#workDone'));
                                    $smsType.each(function () {
                                        smsType += $(this).val() + ',';
                                    });
                                    var $attachments = $('#demo3').find('input[type="hidden"]');
                                    $attachments.each(function () {
                                        attachmentId += $(this).val();
                                        attachmentName += $(this).data('attachname') + ',';
                                    });

                                    if (!neirong1) {
                                        layer.msg('请输入办理汇报！', {icon: 2});
                                        return false;
                                    }

                                    $.ajax({
                                        type: 'get',
                                        url: '/flowAssign/update',
                                        dataType: 'json',
                                        data: {
                                            taskFeedback: neirong1,
                                            flowId: flowId,
                                            smsType: smsType,
                                            smsContent: tipMsg,
                                            runId: runId,
                                            prcsId: globalData.flowRunPrcs.prcsId,
                                            currentPrcsId: globalData.flowProcesses.prcsId,
                                            fdAttachmentName: attachmentName,
                                            fdAttachmentID: attachmentId,
                                            assignId: tData.assignId,
                                            id: globalData.flowRunPrcs.id,
                                            tableName: tableName,
                                            tabId: tabId,
                                            runName: globalData.flowRun.runName,
                                        },
                                        success: function (res) {
                                            if (res.flag) {
                                                // tableIns.reload();
                                                // layer.closeAll();
                                                // $('#neirong1').val('');
                                                // $('#demo3').empty();
                                                // window.close();
                                                $.layerMsg({content: '办理成功', icon: 1}, function () {
                                                    setTimeout(function () {
                                                        window.close();
                                                        if (parent.opener.openRold) {
                                                            parent.opener.openRold()
                                                        }
                                                    }, 100);
                                                });
                                            } else {
                                                layer.msg('办理失败', {icon: 2});
                                            }
                                        }
                                    })
                                },
                                btn2: function () {
                                    layer.closeAll();
                                    $('#neirong1').val('');
                                    $('#demo3').empty();
                                },
                                cancel: function () {
                                    layer.closeAll();
                                    $('#neirong1').val('');
                                    $('#demo3').empty();
                                }
                            });
                        } else {
                            $.layerMsg({content: '保存失败！', icon: 2}, function () {

                            });
                        }
                    })
                }
            } else if (layEvent === '2') { // 工作交办
                // 经办人办理
                if (!!$('#foot_rig').is(':hidden')) {
                    var loadingIndex = layer.load();
                    saveFormSign(loadingIndex, function () {
                        layer.open({
                            title: '<span style="color: #fff;">工作交办</span>',
                            type: 1,
                            area: ['600px', '370px'],
                            content: $('#work'),
                            btn: ['确定', '取消'],
                            success: function () {

                                if (globalData.feedback == 0) {
                                    $("#yesr").attr("checked", true)
                                    $("#nor").attr("disabled", false)
                                }
                                if (globalData.feedback == 1) {
                                    $("#yesr").attr("checked", false)
                                    $("#nor").attr("checked", "checked")
                                }
                                form.render()
                            }
                            , yes: function () {
                                var neirong = ''; //$("#neirong").val().trim();
                                var flowId = $.GetRequest().flowId;
                                var runId = $.GetRequest().runId;
                                var thisrunName = $('.num').attr('thisrunName') || '';
                                // var prcsId = $.GetRequest().flowStep || '';
                                var tableName = $.GetRequest().tableName || '';
                                var jingbanUser = $('#chargePerson').attr('user_id') || '';
                                var viewUser = $('#viewUserName').attr('user_id') || '';
                                var tipMsg = '您有新的公文需要办理，流水号：' + globalData.flowRun.runId + '，工作名称/文号：' + globalData.flowRun.runName
                                var smsType1 = '';
                                var attachmentId = '';
                                var attachmentName = '';

                                if (jingbanUser == '') {
                                    layer.msg('请选择办理人！', {icon: 2});
                                    return false;
                                }

                                var $smsType1 = $('input[name="smstype"]:checkbox:checked', $('#work'));
                                $smsType1.each(function () {
                                    smsType1 += $(this).val() + ',';
                                });

                                var $attachments = $('#demo2').find('input[type="hidden"]');
                                $attachments.each(function () {
                                    attachmentId += $(this).val();
                                    attachmentName += $(this).data('attachname') + ',';
                                });

                                $.ajax({
                                    type: 'post',
                                    url: '/flowAssign/saveWork2',
                                    dataType: 'json',
                                    data: {
                                        assignTask: neirong,
                                        flowId: flowId,
                                        runId: runId,
                                        thisrunName: thisrunName,
                                        tableName: tableName,
                                        jingbanUser: jingbanUser,
                                        viewUser: viewUser + ',',
                                        prcsflag: 1,
                                        prcsId: globalData.flowRunPrcs.prcsId,
                                        currentPrcsId: globalData.flowProcesses.prcsId,
                                        flowPrcs: globalData.flowPrcs,
                                        signYn: globalData.feedback,
                                        prcsName: globalData.prcsName,
                                        attachmentId: attachmentId,
                                        attachmentName: attachmentName,
                                        smsType: smsType1,
                                        smsContent: tipMsg,
                                        assignId: tData.assignId,
                                        topFlag: globalData.flowRunPrcs.topFlag,
                                        parent: globalData.flowRunPrcs.parent
                                    },

                                    success: function (res) {
                                        if (res.flag) {
                                            // tableIns.reload();
                                            // layer.closeAll();
                                            // // 清空内容
                                            // $('#neirong').val('');
                                            // // 清空交办人
                                            // $('#chargePerson').get(0).setAttribute('user_id', '');
                                            // $('#chargePerson').val('');
                                            // // 清空附件信息
                                            // $('#demo2').empty();
                                            // window.close();
                                            $.layerMsg({content: '交办成功', icon: 1}, function () {
                                                setTimeout(function () {
                                                    window.close();
                                                    if (parent.opener.openRold) {
                                                        parent.opener.openRold()
                                                    }
                                                }, 100);
                                            });
                                        } else {
                                            layer.msg('交办失败', {icon: 2});
                                        }
                                    }
                                })
                            },
                            btn2: function () {
                                layer.closeAll();
                                // 清空内容
                                $('#neirong').val('');
                                // 清空交办人
                                $('#chargePerson').get(0).setAttribute('user_id', '');
                                $('#chargePerson').val('');
                                // 清空附件信息
                                $('#demo2').empty();
                            },
                            cancel: function () {
                                layer.closeAll();
                                // 清空内容
                                $('#neirong').val('');
                                // 清空交办人
                                $('#chargePerson').get(0).setAttribute('user_id', '');
                                $('#chargePerson').val('');
                                // 清空附件信息
                                $('#demo2').empty();
                            }
                        });
                    });
                } else { // 主办人办理
                    saveFlowData(function (data) {
                        if (data.flag) {
                            layer.open({
                                title: '<span style="color: #fff;">工作交办</span>',
                                type: 1,
                                area: ['600px', '370px'],
                                content: $('#work'),
                                btn: ['确定', '取消'],
                                success: function () {

                                    if (globalData.feedback == 0) {
                                        $("#yesr").attr("checked", true)
                                        $("#nor").attr("disabled", false)
                                    }
                                    if (globalData.feedback == 1) {
                                        $("#yesr").attr("checked", false)
                                        $("#nor").attr("checked", "checked")
                                    }
                                    form.render()
                                }
                                , yes: function () {
                                    var neirong = ''; //$("#neirong").val().trim();
                                    var flowId = $.GetRequest().flowId;
                                    var runId = $.GetRequest().runId;
                                    var thisrunName = $('.num').attr('thisrunName') || '';
                                    // var prcsId = $.GetRequest().flowStep || '';
                                    var tableName = $.GetRequest().tableName || '';
                                    var jingbanUser = $('#chargePerson').attr('user_id') || '';
                                    var viewUser = $('#viewUserName').attr('user_id') || '';
                                    var tipMsg = '您有新的公文需要办理，流水号：' + globalData.flowRun.runId + '，工作名称/文号：' + globalData.flowRun.runName
                                    var smsType1 = '';
                                    var attachmentId = '';
                                    var attachmentName = '';

                                    if (jingbanUser == '') {
                                        layer.msg('请选择办理人！', {icon: 2});
                                        return false;
                                    }

                                    var $smsType1 = $('input[name="smstype"]:checkbox:checked', $('#work'));
                                    $smsType1.each(function () {
                                        smsType1 += $(this).val() + ',';
                                    });

                                    var $attachments = $('#demo2').find('input[type="hidden"]');
                                    $attachments.each(function () {
                                        attachmentId += $(this).val();
                                        attachmentName += $(this).data('attachname') + ',';
                                    });

                                    $.ajax({
                                        type: 'post',
                                        url: '/flowAssign/saveWork2',
                                        dataType: 'json',
                                        data: {
                                            assignTask: neirong,
                                            flowId: flowId,
                                            runId: runId,
                                            thisrunName: thisrunName,
                                            tableName: tableName,
                                            jingbanUser: jingbanUser,
                                            viewUser: viewUser + ',',
                                            prcsflag: 1,
                                            prcsId: globalData.flowRunPrcs.prcsId,
                                            currentPrcsId: globalData.flowProcesses.prcsId,
                                            flowPrcs: globalData.flowPrcs,
                                            signYn: globalData.feedback,
                                            prcsName: globalData.prcsName,
                                            attachmentId: attachmentId,
                                            attachmentName: attachmentName,
                                            smsType: smsType1,
                                            smsContent: tipMsg,
                                            assignId: tData.assignId,
                                            topFlag: globalData.flowRunPrcs.topFlag,
                                            parent: globalData.flowRunPrcs.parent
                                        },

                                        success: function (res) {
                                            if (res.flag) {
                                                // tableIns.reload();
                                                // layer.closeAll();
                                                // // 清空内容
                                                // $('#neirong').val('');
                                                // // 清空交办人
                                                // $('#chargePerson').get(0).setAttribute('user_id', '');
                                                // $('#chargePerson').val('');
                                                // // 清空附件信息
                                                // $('#demo2').empty();
                                                // window.close();
                                                $.layerMsg({content: '交办成功', icon: 1}, function () {
                                                    setTimeout(function () {
                                                        window.close();
                                                        if (parent.opener.openRold) {
                                                            parent.opener.openRold()
                                                        }
                                                    }, 100);
                                                });
                                            } else {
                                                layer.msg('交办失败', {icon: 2});
                                            }
                                        }
                                    })
                                },
                                btn2: function () {
                                    layer.closeAll();
                                    // 清空内容
                                    $('#neirong').val('');
                                    // 清空交办人
                                    $('#chargePerson').get(0).setAttribute('user_id', '');
                                    $('#chargePerson').val('');
                                    // 清空附件信息
                                    $('#demo2').empty();
                                },
                                cancel: function () {
                                    layer.closeAll();
                                    // 清空内容
                                    $('#neirong').val('');
                                    // 清空交办人
                                    $('#chargePerson').get(0).setAttribute('user_id', '');
                                    $('#chargePerson').val('');
                                    // 清空附件信息
                                    $('#demo2').empty();
                                }
                            });
                        } else {
                            $.layerMsg({content: '保存失败！', icon: 2}, function () {

                            });
                        }
                    })
                }
            }
        });

        function initAssignmentTable() {
            tableIns = table.render({
                elem: '#assignmenttable'
                , url: '/flowAssign/query?runId=' + runId
                , page: false
                , cols: [[
                    {field: 'flowPrcs', align:'center', title: '步骤', width: 100,
                            templet: function (d) {
                                return '第' + d.flowPrcs + '步';
                            }
                        },
                        {field: 'prcsName', align:'center',title: '名称', width: 160},
                        {field: 'assignUserName', align:'center',title: '交办人', width: 100,
                            templet: function (d) {
                                return d.assignUserName + '<input class="parentassignid" type="hidden" value="'+d.parentAssignId+'"/>';
                            }
                        },
                        {field: 'handleUserName', align:'center',title: '办理人', width: 100},
                        // {field: 'assignTask', align:'center',title: '交办任务', minWidth: 100},
                        {field: 'handleStatus', align:'center',title: '状态', width: 100,
                            templet: function (d) {
                                var str = '未接收';
                                if (d.handleStatus == 1) {
                                    str = '办理中';
                                } else if (d.handleStatus == 2) {
                                    str = '办结';
                                }
                                return str;
                            }
                        },
                        {field: 'assignTime', align:'center',title: '交办时间', width: 150,templet: function(d){
                        // 格式化时间为 'YYYY/MM/DD mm:dd:ss'  否则ie下 new Date() 方法会出错
                                            var dateStr = d.assignTime.replace(/-/g,"/");
                                            return new Date(dateStr).Format('yyyy-MM-dd hh:mm');
                        }},
                        {field: 'attachmentName', align:'center',title: '交办文件', minWidth: 120,
                            templet: function (d) {
                                var attachmentList = d.attachment;
                                var str = ''
                                if (attachmentList.length > 0) {
                                    attachmentList.forEach(function(item){
                                        var fileExtension=item.attachName.substring(item.attachName.lastIndexOf(".")+1,item.attachName.length);//截取附件文件后缀
                                        var attName = encodeURI(item.attachName).replace(/\+/g, "%2b").replace(/\@/g,"%40").replace(/\#/g,"%23").replace(/\&/g,"%26").replace(/\//g,"%2F").replace(/\?/g,"%3F").replace(/\￥/g,"%ef%bf%a5").replace(/\$/g,"%24").replace(/\！/g,"%ef%bc%81").replace(/\（/g,"%ef%bc%88").replace(/\）/g,"%ef%bc%89").replace(/\…/g,"%e2%80%a6%e2%80%a6");
                                        var fileExtensionName=attName.substring(0,attName.lastIndexOf("."));
                                        var deUrl = item.attUrl.split('&ATTACHMENT_NAME=')[0]+"&ATTACHMENT_NAME="+fileExtensionName+"."+fileExtension+"&FILESIZE="+item.size;

                                        str+= '<div class="divShow"><a href="javascript:;" title="'+item.attachName+'" style="display: block; overflow: hidden;text-overflow: ellipsis;">'+item.attachName+'</a>' +
                                            '<div class="operationDiv">'+function(){
                                                if(fileExtension == 'pdf' || fileExtension == 'PDF'|| fileExtension == 'png' || fileExtension == 'PNG' || fileExtension == 'jpg' || fileExtension == 'JPG'|| fileExtension == 'txt'|| fileExtension == 'TXT') { //判断是否需要查阅
                                                    return '<a class="operation yulan"  href="javascript:void(0);" data-url="' + encodeURI(deUrl) + '" style="display: block; padding-left: 10px;"><img src="/img/attachmentIcon/icon_skim.png" style="margin-right: 5px;" alt="">查阅</a>'
                                                }else{
                                                    return '<a class="operation yulan"  href="javascript:void(0);" data-url="' + deUrl + '" style="display: block;padding-left: 10px;"><img src="/img/attachmentIcon/icon_skim.png" style="margin-right: 5px;" alt="">查阅</a>'
                                                }
                                            }()+
                                            '<a class="operation" style="display: block;padding-left: 10px;" href="/download?' + encodeURI(deUrl) + '"><img src="/img/attachmentIcon/icon_down.png" style="margin-right: 5px;" alt="">下载</a>'
                                            +'</div>' +
                                            '</div>'
                                    })
                                }
                                return str;
                            }
                        },
                        // {field: 'handleHour', align:'center',title: '时限', minWidth: 80},
                        // {field: 'receiveTime', align:'center',title: '任务接收时间', minWidth: 180},
                        {field: 'taskFeedback', align:'center',title: '办理汇报', minWidth: 120},
                        {field: 'fdAttachmentName', align:'center',title: '汇报文件', minWidth: 120,
                            templet: function (d) {
                                var attachmentList = d.fdAttachment;
                                var str = ''
                                if (attachmentList.length > 0) {
                                    attachmentList.forEach(function(item){
                                        var attachName = item.attachName;
                                        var fileExtension=attachName.substring(attachName.lastIndexOf(".")+1,attachName.length);//截取附件文件后缀
                                        var attName = encodeURI(attachName).replace(/\+/g, "%2b").replace(/\@/g,"%40").replace(/#/g,"%23").replace(/\&/g,"%26").replace(/\//g,"%2F").replace(/\?/g,"%3F").replace(/\￥/g,"%ef%bf%a5").replace(/$/g,"%24").replace(/\！/g,"%ef%bc%81").replace(/\（/g,"%ef%bc%88").replace(/\）/g,"%ef%bc%89").replace(/\…/g,"%e2%80%a6%e2%80%a6");
                                        var fileExtensionName=attName.substring(0,attName.lastIndexOf("."));
                                        var attachmentUrl = item.attUrl;
                                        attachmentUrl = attachmentUrl.substring(0,attachmentUrl.lastIndexOf("ATTACHMENT_NAME="))+"ATTACHMENT_NAME="+fileExtensionName+"."+fileExtension; //处理附件名字

                                        str+= '<div class="divShow"><a href="javascript:;" title="'+item.attachName+'" style="display: block; overflow: hidden;text-overflow: ellipsis;">'+item.attachName+'</a>' +
                                            '<div class="operationDiv">'+function(){
                                                if(fileExtension == 'pdf' || fileExtension == 'PDF'|| fileExtension == 'png' || fileExtension == 'PNG' || fileExtension == 'jpg' || fileExtension == 'JPG'|| fileExtension == 'txt'|| fileExtension == 'TXT') { //判断是否需要查阅
                                                    return '<a class="operation yulan"  href="javascript:void(0);" data-url="' + encodeURI(attachmentUrl) + '" style="display: block;padding-left: 10px;"><img src="/img/attachmentIcon/icon_skim.png" style="margin-right: 5px;" alt="">查阅</a>'
                                                }else{
                                                    return '<a class="operation yulan"  href="javascript:void(0);" data-url="' + attachmentUrl + '" style="display: block;padding-left: 10px;"><img src="/img/attachmentIcon/icon_skim.png" style="margin-right: 5px;" alt="">查阅</a>'
                                                }
                                            }()+
                                            '<a class="operation" style="display: block;padding-left: 10px;" href="/download?' + encodeURI(attachmentUrl) + '"><img src="/img/attachmentIcon/icon_down.png" style="margin-right: 5px;" alt="">下载</a>'
                                            +'</div>' +
                                            '</div>'
                                    })
                                }
                                return str;
                            }},
                        {fixed: 'right', title: '操作',align:'center', toolbar: '#assignmentBar', width: 120}
                ]],
                done: function (res) {
                    layer.closeAll();
                    if (!res.flag) {
                        $('#assignmentDetail').hide();
                        return false;
                    }
                    $('#assignmentDetail').show();
                    $('.divShow').parent().css('height', 'auto');
                    $('.divShow').parent().css('overflow', 'visible');
                    $('#assignmentDetail .layui-table-main tr').last().find('.operationDiv').css('top', '-210%');
                    merge(res);
                }
                , response: {
                    statusName: 'flag',
                    statusCode: true,
                    dataName: 'object'
                }
            });
        }

        // 合并单元格方法
        function merge(res) {
            var data = res.object;
            var mergeIndex = 0;//定位需要添加合并属性的行数
            var mark = 1; //这里涉及到简单的运算，mark是计算每次需要合并的格子数
            var columsName = ['flowPrcs', 'prcsName', 'parentAssignId'];//需要合并的列名称
            var columsIndex = [0, 1, 2];//需要合并的列索引值

            var toolArr = $(".layui-table-fixed>.layui-table-body>.layui-table").find("tr");

            for (var k = 0; k < columsName.length; k++) { //这里循环所有要合并的列
                var trArr = $(".layui-table-main>.layui-table").find("tr");//所有行
                for (var i = 1; i < data.length; i++) { //这里循环表格当前的数据
                    var tdCurArr = trArr.eq(i).find("td").eq(columsIndex[k]);//获取当前行的当前列
                    var tdPreArr = trArr.eq(mergeIndex).find("td").eq(columsIndex[k]);//获取相同列的第一列
                    toolArr.eq(i - 1).css({
                        height: function () {
                            return trArr.eq(i - 1).height();
                        }
                    });
                    if (data[i][columsName[k]] === data[i - 1][columsName[k]]) { //后一行的值与前一行的值做比较，相同就需要合并
                        if (k == 2 && (data[i]['flowPrcs'] != data[i - 1]['flowPrcs'])) {
                            mergeIndex = i;
                            mark = 1;//一旦前后两行的值不一样了，那么需要合并的格子数mark就需要重新计算
                            continue;
                        }
                        mark += 1;
                        tdPreArr.each(function () {//相同列的第一列增加rowspan属性
                            $(this).attr("rowspan", mark);
                        });
                        tdCurArr.each(function () {//当前行隐藏
                            $(this).css("display", "none");
                        });
                    } else {
                        mergeIndex = i;
                        mark = 1;//一旦前后两行的值不一样了，那么需要合并的格子数mark就需要重新计算
                    }
                }
                mergeIndex = 0;
                mark = 1;
            }
        }

    });

    //选择意见
    $("#assignmentSign").click(function () {
        var signChooseLayer = layer.open({
            title: '<span style="color: #fff;">选择常用意见</span>',
            area: ['800px', '600px'],
            type: 1,
            content: '<div id="saveRule" >' +
                '<div class="layui-form-item" style="margin: 10px 0 0 0;">' +
                '<label class="layui-form-label" style="font-size: 13px; width: 100px;">添加常用意见：</label>' +
                '<div class="layui-input-block" style="margin-left: 130px;">' +
                '<input type="text" id="yijian" style="width: 300px" ><button type="button" style="font-size: 13px" class="add_fujianss" id="add">添加</button>' +
                '<a style="margin-left:30px;margin-top:-13px;color:red;font-size: 13px;cursor:pointer;text-decoration: none;" id="up">删除常用意见</a>' +
                '</div>' +
                '</div>' +
                '<div class="inputlayout" style="height: 440px; overflow: hidden;">' +
                '<ul class="input_radio_box" style="height: 100%; overflow-y: auto;"></ul>' +
                '</div>' +
                '<hr>' +
                '<div style="text-align: center;">' +
                '<button type="button" style="margin: 0 10px;font-size: 13px" class="add_fujians" id="yes">选择</button>' +
                '<button type="button" style="margin: 0 10px;font-size: 13px" class="add_fujians" id="cancle">取消</button>' +
                '</div>' +
                '</div>'
            ,
            success: function () {
                $.get('/flowOpinion/selectFlowOpinion', function (res) {
                    var data = res.object
                    if (res.flag) {
                        if (res.object.length > 0) {
                            var str = ''
                            for (var i = 0; i < data.length; i++) {
                                str += '<li class="clearfix" style="font-size: 13px;line-height: 20px;padding: 0 10px;"><input style="margin: -2px 5px 0 15px;" class="tableDl " id="flowId" data-id="' + data[i].opinionId + '"  type="radio" name="flowId" value="' + data[i].opinionContent + '" >' + data[i].opinionContent + '</li>'
                            }
                            $('.input_radio_box').html(str);
                        }
                    }
                });
                //数据回显
                $("#yes", $('#saveRule')).click(function (event) {
                    var oldVal = $("#neirong").val();
                    var opinionContent = $('input[name="flowId"]:checked').val()

                    $("#neirong").val(oldVal + opinionContent);
                    layer.close(signChooseLayer);
                })

                //添加意见
                $("#add", $('#saveRule')).click(function (event) {
                    var content = document.getElementById("yijian").value

                    $.ajax({
                        type: 'post',
                        url: '/flowOpinion/insertFlowOpinion',
                        dataType: 'json',
                        data: {
                            opinionContent: content,
                            opinionType: 1,

                        },
                        success: function (res) {
                            if (res.flag) {
                                $.get('/flowOpinion/selectFlowOpinion', function (res) {
                                    var data = res.object
                                    if (res.flag) {
                                        if (res.object.length > 0) {
                                            var str = ''
                                            for (var i = 0; i < data.length; i++) {
                                                str += '<li class="clearfix" style="font-size: 13px;line-height: 20px;padding: 0 10px;"><input style="margin: -2px 5px 0 15px;" class="tableDl " id="flowId" data-id="' + data[i].opinionId + '"  type="radio" name="flowId" value="' + data[i].opinionContent + '" >' + data[i].opinionContent + '</li>'
                                            }
                                            $('.input_radio_box').html(str);
                                        }
                                    }
                                    $("#yijian").attr("value", "");

                                });
                            }
                        }
                    })
                })

                //删除意见
                $("#up", $('#saveRule')).click(function () {
                    var opinionId = $('input[name="flowId"]:checked').data('id')

                    $.layerConfirm({title: '确定删除', content: '您确定要删除吗?', icon: 0}, function () {
                        $.ajax({
                            type: 'post',
                            url: '/flowOpinion/delFlowOpinion',
                            dataType: 'json',
                            data: {
                                opinionId: opinionId,
                            },
                            beforeSend: function (request) {
                                if (beforeToken != '') {
                                    request.setRequestHeader("Authorization", 'Bearer ' + beforeToken);
                                }
                            },
                            success: function (res) {
                                if (res.flag) {
                                    $.get('/flowOpinion/selectFlowOpinion', function (res) {
                                        var data = res.object
                                        if (res.flag) {
                                            if (res.object.length > 0) {
                                                var str = ''
                                                for (var i = 0; i < data.length; i++) {
                                                    str += '<li class="clearfix" style="font-size: 13px;line-height: 20px;padding: 0 10px;"><input style="margin: -2px 5px 0 15px;" class="tableDl" id="flowId" data-id="' + data[i].opinionId + '"  type="radio" name="flowId" value="' + data[i].opinionContent + '" >' + data[i].opinionContent + '</li>'
                                                }
                                                $('.input_radio_box').html(str);
                                            }
                                        }
                                    });
                                } else {
                                    $.layerMsg({content: '请选择意见', icon: 2})
                                }
                            }
                        })
                    })
                })

                // 取消添加意见
                $("#cancle", $('#saveRule')).click(function () {
                    layer.close(signChooseLayer)
                })
            }
        });
    });

    // 工作交办-获取办理人
    $('#userAdd').click(function () {
        user_id = "chargePerson";
        // $.popWindow("../../common/selectUser");
        selectUserLayerIndex = layer.open({
            title: '<span style="color: #fff;">选择用户</span>',
            type: 2,
            content: '/common/selectUser_iframe?isIframeOpen=1&&selectUserLayerIndex=selectUserLayerIndex', // 专用iframe打开的选人控件页面
            area: ['60%', '70%']
        });
    });
    // 工作交办-清空办理人
    $('#delUser').click(function () {
        $('#chargePerson').get(0).setAttribute('user_id', '');
        $('#chargePerson').val('');
    });

    /***********************关联操作(分发、补发、交办、集团发文) END**************************/

    // 一键下载文件
    $('#downloadFiles').click(function () {
        var fileIndex = layer.open({
            type: 1,
            title: '<span style="color: #fff;">文件下载</span>',
            area: ['700px', '70%'],
            content: '<div>' +
                '<div class="form_files">' +
                '<h3 style="text-align: center;background-color: #d6e7f8;">' +
                '<label style="position: absolute;left: 20px;font-size: 100%;margin: 0; line-height: 25px;"><input id="formFilesInputAll" onclick="checkFileInput(this, 0, 1)" type="checkbox" style="margin: 6px 5px;outline: none;">全选</label><span>表单文件</span>' +
                '</h3><ul></ul>' +
                '</div>' +
                '<div class="common_files">' +
                '<h3 style="text-align: center;background-color: #d6e7f8;">' +
                '<label style="position: absolute;left: 20px;font-size: 100%;margin: 0; line-height: 25px;"><input id="commonFilesInputAll" onclick="checkFileInput(this, 0, 2)" type="checkbox" style="margin: 6px 5px;outline: none;">全选</label><span>公共文件</span>' +
                '</h3><ul></ul>' +
                '</div>' +
                '<div class="main_files">' +
                '<h3 style="text-align: center;background-color: #d6e7f8;">' +
                '<label style="position: absolute;left: 20px;font-size: 100%;margin: 0; line-height: 25px;"><input id="mainFilesInputAll" onclick="checkFileInput(this, 0, 3)" type="checkbox" style="margin: 6px 5px;outline: none;">全选</label><span>正文文件</span>' +
                '</h3><ul></ul>' +
                '</div>' +
                '</div>',
            btn: ['确定', '取消'],
            success: function () {
                // 获取表单文件
                var formFiles = $('#client').find('.imgfileBox');
                var formFilesStr = '';
                formFiles.each(function (i, v) {
                    var atturl = $(v).find('img').attr('atturl') || '';
                    if (!!atturl) {
                        var aId = getUrlString('AID', atturl);
                        var attachmentId = getUrlString('ATTACHMENT_ID', atturl);
                        var ym = getUrlString('YM', atturl);
                        var id = aId + '@' + ym + '_' + attachmentId;
                        var attachName = getUrlString('ATTACHMENT_NAME', atturl);
                        var module = getUrlString('MODULE', atturl);
                        formFilesStr += '<li style="line-height: 22px;"><input style="outline: none;" class="download_file_input form_files_input" fileType="1"  onclick="checkFileInput(this, 1, 1)" type="checkbox" attachmentId="' + id + '" attachName="' + attachName + '" module="' + module + '" name=""/>' + attachName + '</li>';
                    }
                })
                if (!!formFilesStr) {
                    $('.form_files ul').html(formFilesStr);
                } else {
                    $('#formFilesInputAll').parent().hide();
                    $('.form_files ul').html('<li style="line-height: 22px;">暂无文件</li>');
                }
                // 获取公共文件
                var commonFileStr = '';
                $.get('/workflow/work/findworkUpload', {
                    runId: $.getQueryString("runId"),
                    randomNum: Math.random()
                }, function (res) {
                    if (res.flag) {
                        res.obj.forEach(function (file) {
                            var atturl = file.attUrl || '';
                            if (!!atturl) {
                                var aId = getUrlString('AID', atturl);
                                var attachmentId = getUrlString('ATTACHMENT_ID', atturl);
                                var ym = getUrlString('YM', atturl);
                                var id = aId + '@' + ym + '_' + attachmentId;
                                var attachName = getUrlString('ATTACHMENT_NAME', atturl);
                                var module = getUrlString('MODULE', atturl);
                                commonFileStr += '<li style="line-height: 22px;"><input style="outline: none;" class="download_file_input common_files_input" fileType="2"  onclick="checkFileInput(this, 1, 2)" type="checkbox" attachmentId="' + id + '" attachName="' + attachName + '" module="' + module + '" name=""/>' + attachName + '</li>';
                            }
                        })
                    }
                    if (!!commonFileStr) {
                        $('.common_files ul').html(commonFileStr);
                    } else {
                        $('#commonFilesInputAll').parent().hide();
                        $('.common_files ul').html('<li style="line-height: 22px;">暂无文件</li>');
                    }
                })
                // 获取正文文件
                var mainFileStr = '';
                $.get('/document/selectDocById', {
                    id: $.getQueryString("tabId"),
                    randomNum: Math.random(),
                    flowId: $.getQueryString('flowId')
                }, function (res) {
                    if (res.flag) {
                        if (!!res.object.wordAttUrl) {
                            var fileStr = res.object.wordAttUrl;
                            var aId = getUrlString('AID', fileStr);
                            var attachmentId = getUrlString('ATTACHMENT_ID', fileStr);
                            var ym = getUrlString('YM', fileStr);
                            var id = aId + '@' + ym + '_' + attachmentId;
                            var attachName = getUrlString('ATTACHMENT_NAME', fileStr);
                            var module = getUrlString('MODULE', fileStr);
                            mainFileStr += '<li style="line-height: 22px;"><input style="outline: none;" class="download_file_input main_files_input" fileType="4" onclick="checkFileInput(this, 1, 3)" type="checkbox" attachmentId="' + id + '" attachName="' + attachName + '" module="' + module + '" name=""/>（留痕正文）' + attachName + '</li>';
                        }
                        if (!!res.object.aipAttUrl) {
                            var fileStr = res.object.aipAttUrl;
                            var aId = getUrlString('AID', fileStr);
                            var attachmentId = getUrlString('ATTACHMENT_ID', fileStr);
                            var ym = getUrlString('YM', fileStr);
                            var id = aId + '@' + ym + '_' + attachmentId;
                            var attachName = getUrlString('ATTACHMENT_NAME', fileStr);
                            var module = getUrlString('MODULE', fileStr);
                            mainFileStr += '<li style="line-height: 22px;"><input style="outline: none;" class="download_file_input main_files_input" fileType="6" onclick="checkFileInput(this, 1, 3)" type="checkbox" attachmentId="' + id + '" attachName="' + attachName + '" module="' + module + '" name=""/>（转版正文）' + attachName + '</li>';
                        }
                        if (!!res.object.mainOriginAttUrl) {
                            var fileStr = res.object.mainOriginAttUrl;
                            var aId = getUrlString('AID', fileStr);
                            var attachmentId = getUrlString('ATTACHMENT_ID', fileStr);
                            var ym = getUrlString('YM', fileStr);
                            var id = aId + '@' + ym + '_' + attachmentId;
                            var attachName = getUrlString('ATTACHMENT_NAME', fileStr);
                            var module = getUrlString('MODULE', fileStr);
                            mainFileStr += '<li style="line-height: 22px;"><input style="outline: none;" class="download_file_input main_files_input" fileType="3" onclick="checkFileInput(this, 1, 3)" type="checkbox" attachmentId="' + id + '" attachName="' + attachName + '" module="' + module + '" name=""/>（原始正文）' + attachName + '</li>';
                        }
                        if (!!res.object.mainClearAttUrl) {
                            var fileStr = res.object.mainClearAttUrl;
                            var aId = getUrlString('AID', fileStr);
                            var attachmentId = getUrlString('ATTACHMENT_ID', fileStr);
                            var ym = getUrlString('YM', fileStr);
                            var id = aId + '@' + ym + '_' + attachmentId;
                            var attachName = getUrlString('ATTACHMENT_NAME', fileStr);
                            var module = getUrlString('MODULE', fileStr);
                            mainFileStr += '<li style="line-height: 22px;"><input style="outline: none;" class="download_file_input main_files_input" fileType="5" onclick="checkFileInput(this, 1, 3)" type="checkbox" attachmentId="' + id + '" attachName="' + attachName + '" module="' + module + '" name=""/>（定稿正文）' + attachName + '</li>';
                        }
                    }
                    if (!!mainFileStr) {
                        $('.main_files ul').html(mainFileStr);
                    } else {
                        $('#mainFilesInputAll').parent().hide();
                        $('.main_files ul').html('<li style="line-height: 22px;">暂无文件</li>');
                    }
                })
            },
            yes: function () {
                var $checkFIles = $('.download_file_input:checked')
                var dataArr = [];
                $checkFIles.each(function (i, v) {
                    var attachmentId = $(v).attr('attachmentId') + ',';
                    var attachName = $(v).attr('attachName') + '*';
                    var module = $(v).attr('module');
                    var type = $(v).attr('fileType');
                    dataArr.push({
                        attachId: attachmentId,
                        attachName: attachName,
                        module: module,
                        type: type
                    })
                })

                if (dataArr.length > 0) {
                    // var url = '/workflow/work/downLoadZipAtt?attachments=' + JSON.stringify(dataArr) + '&flowName=' +globalData.flowRun.runName;
                    $.dynamicSubmit('/workflow/work/downLoadZipAtt', {
                        "attachments": JSON.stringify(dataArr),
                        "flowName": globalData.flowRun.runName
                    }, function () {
                        layer.close(fileIndex);
                    });
                    // location.href = encodeURI(url).replace(/#/g, '%2523');
                }
            }
        })
    });
  
    // 修改新闻内容
    $(document).on('click', '.edit_news_content', function () {
        var newsId = $(this).attr('newsid');
        
        // 新建新闻编辑器
        var newKindEditorObj = null;
        
        layer.open({
            type: 1,
            title: '<span style="color: #fff;">新闻内容</span>',
            btn: ['保存', '取消'],
            area: ['1000px', '600px'],
            content: '<div id="newsEditBox" style="height: 100%;"><textarea id="kindEditor" name="content" style="width: 100%; height: 490px"></textarea></div>',
            success: function () {
                var kindEditorOption = {
                    themeType: 'simple', // 定义编辑器为简洁模式
                    filterMode: false, // 开启过滤
                    allowFileManager: true, // 开启文件空间
                    uploadJson: '/ueditor/upload?module=ueditor', // 上传接口
                    filePostName: 'upfile', // 自定义后台接收的文件流参数名（默认为 imgFile）
                    afterUploadStatusName: 'state', // 定义上传后判断的参数名（默认为 error）
                    afterUploadSuccessCode: 'SUCCESS', // 定义上传成功后参数值（默认为 0）此处判断为===，必须保证类型也相同
                    afterUploadErrorMsg: 'msg', // 定义上传失败后提示信息的参数名（默认为 message）
                }
                // 必须使用这个方法初始化编辑器，否则编辑器无法显示
                newKindEditorObj = KindEditor.create('#kindEditor', kindEditorOption);
                $.get('/news/getOneById', {newsId: newsId, changId: "1"}, function (res) {
                    if (res.flag) {
                        newKindEditorObj.html(res.object.content);
                    }
                });
            },
            yes: function (index) {
                var contentHtml = newKindEditorObj.html();
                $.post('/news/updateContent', {newsId: newsId, content: contentHtml}, function(res){
                    if (res.flag) {
                        layer.msg('保存成功', {icon: 1, time: 1000});
                        layer.close(index);
                    } else {
                        layer.msg('保存失败', {icon: 2, time: 1000});
                    }
                });
            }
        });
    });
});

function initConnectTable(runId, isInit) {
    $('.connect_flow', $('#relevantProcessesTbody')).remove();
    $.get('/flowRun/findrelationRunIds', {runId: runId}, function (res) {
        if (res.flag) {
            var $connectMacrossEle = $('.macrossign[datafld="SYS_FLOW_CONNECTFLOW"]');
            var str = '';
            var str2 = '';
            var lastObj = null;
            if (res.obj.length > 0) {
                lastObj = res.obj[res.obj.length-1];
                res.obj.forEach(function (item) {
                    var delStr = '';
                    if (item.isDelete == '1') {
                        delStr = '<button relationrunid="' + item.runId + '" class="layui-btn layui-btn-xs layui-btn-danger del_connect_btn" style="float: right;">删除</button>';
                    }
                    str += '<li style="padding: 5px;"><span style="display: inline-block; width: 40px; text-align: center;vertical-align: middle;">' + item.runId + '</span><a class="open_flow_work" title="' + item.runName + '" runid="' + item.runId + '" flowid="' + item.flowId + '" href="javascript:;" style="display: inline-block;margin-left: 20px;color: blue;vertical-align: middle; max-width: 165px;word-break: break-all;white-space: nowrap;text-overflow: ellipsis;overflow: hidden;text-decoration: none;">' + item.runName + '</a>' + delStr + '</li>';
                    str2 += '<tr class="connect_flow"><td>关联流程</td><td><a style="color: #1687cb;text-decoration: underline;cursor: pointer;" class="open_flow_work" title="' + item.runName + '" runid="' + item.runId + '" flowid="' + item.flowId + '" href="javascript:;">' + item.runName + '</a></td></tr>'
                });
                $('#relevantProcessesTbody').append(str2);
                $('#connectList').html(str);
                $('.noData1').hide();
                $('#connectList').show();
                $('#relevantProcesses').show();
            } else {
                if ($('#uxiangqing').children().length == 0) {
                    $('.noData1').show();
                }
                if ($('#relevantProcessesTbody').children().length == 0) {
                    $('#relevantProcesses').hide();
                }
                $('#connectList').hide();
            }
            if (!isInit) {
                var $connectMacrossEle = $('.macrossign[datafld="SYS_FLOW_CONNECTFLOW"]');
                if ($connectMacrossEle.length > 0) {
                    $connectMacrossEle.each(function () {
                        // $.each(this.attributes, function () {
                        //     if (this.specified) {
                        //         console.log(this.name, this.value);
                        //     }
                        // });
                        var isDisabled = $(this).attr('disabled') || '';
                        var ismust = $(this).attr('ismust') || false;
                        if (isDisabled != 'disabled') {
                            var str = '';
                            if (lastObj) {
                                var str2 = '<ul>' +
                                    '<li style="color: #000;"><span>关联流程：</span><a class="open_flow_work" href="javascript:;" runid="' + lastObj.runId + '" flowid="' + lastObj.flowId + '" style="text-decoration: none; color: #2567d6;">' + lastObj.runName + '</a></li>' +
                                    '<li style="color: #000;"><span>流转节点：</span><span>' + (lastObj.allUserName || '') + '</span></li>' +
                                    '<li style="color: #000;"><span>说<span style="display: inline-block;text-indent: 2em;color: #000;">明：</span></span><span>关联流程中已审核通过的领导节点，本流程可跳过</span></li>' +
                                    '</ul>';
                                str = '<span id="' + $(this).attr('name') + '" flowtype="2" name="' + $(this).attr('name') + '" title="' + $(this).attr('title') + '" data-type="' + $(this).attr('data-type') + '" style="' + $(this).attr('style') + 'overflow: hidden;text-align:left;vertical-align:middle;" class="form_item macrossign" datafld="' + $(this).attr('datafld') + '" stepType = "' + $(this).attr('stepType') + '" '+isDisabled+' ismust="' + ismust + '">' + str2 + '</span>';
                            } else {
                                var value = globalData.option.dataName ? globalData.option.dataName[$(this).attr('name')] || '' : '';
                                if (value.indexOf('<ul>') > -1) {
                                    value = '';
                                }
                                str = '<input type="text" value="' + value + '" id="' + $(this).attr('name') + '" flowtype="1" name="' + $(this).attr('name') + '" title="' + $(this).attr('title') + '" data-type="' + $(this).attr('data-type') + '" style="' + $(this).attr('style') + 'overflow: hidden;text-align:left;vertical-align:middle;" class="form_item macrossign" datafld="' + $(this).attr('datafld') + '" stepType = "' + $(this).attr('stepType') + '" '+isDisabled+' ismust="' + ismust + '" placeholder="请输入未关联流程原因">';
                            }
                            $(this).replaceWith(str);
                        }
                    });
                }
            }
        }
    });
}

function buildNode(len, data) {
    var prefix = 10;
    for (var i = 0; i < len; i++) {
        prefix += 10;
    }

    $.each(data, function (i, item) {
        if (0 < item.childs.length) {
            $('.sel').append("<li style='padding-left:" + (prefix) + "px;font-weight:bold;font-size:14px;' id=" + item.sortId + ">" + item.sortName + "<li>");
            $.each(item.flowTypeModels, function (j, v) {
                $('.sel').append("<li style='padding-left:" + (prefix + 10) + "px;cursor:pointer' class='canchoose' value=" + v.flowId + ">" + v.flowName + "<li>");
            })
            buildNode(len + 1, item.childs);
        } else {
            $('.sel').append("<li style='padding-left:" + (prefix) + "px;font-weight:bold;font-size:14px;' id=" + item.sortId + ">" + item.sortName + "<li>");
            $.each(item.flowTypeModels, function (j, v) {
                $('.sel').append("<li style='padding-left:" + (prefix + 10) + "px;cursor:pointer' class='canchoose' value=" + v.flowId + ">" + v.flowName + "<li>");
            })
        }
    });
}

function searchConnectWork(target) {
    var runId = $('.cw_runid').val() || '';
    var flowId = $('.cw_flowid').attr('dataType') || '';
    var runName = $('.cw_runname').val() || '';
    $.get('/flowRun/findFLow', {runId: runId, flowId: flowId, runName: runName}, function (res) {
        if (res.flag) {
            var str = '';
            if (res.obj.length > 0) {
                res.obj.forEach(function (item) {
                    str += '<tr><td style="padding: 5px;text-align: left;">' + item['runId'] + '</td><td style="width: 60%;padding: 5px;text-align: left;"><a style="cursor: pointer;text-decoration: underline;" class="open_flow_work" flowid="' + item['flowId'] + '" runid="' + item['runId'] + '">' + item['runName'] + '</a></td><td style="padding: 5px;"><a relationrunid="' + item['runId'] + '" runname="' + item['runName'] + '" href="javascript:;" class="add_connect_btn" style="color: blue;">添加</a></td></tr>'
                });
            }
            $('#connectTable').html(str);
        }
    });
}

function getUrlString(name, url) {
    var reg = new RegExp("(^|&)" + name + "=([^&]*)(&|$)", "i");
    re = new RegExp("amp;", "g"); //定义正则表达式
    var r = url.match(reg);
    var context = "";
    if (r != null)
        context = r[2];
    reg = null;
    r = null;
    return context == null || context == "" || context == "undefined" ? "" : context;
}

// 附件全选、单选
function checkFileInput(e, allType, fileType) {
    var allInput = '';
    var fileInput = '';
    switch (fileType) {
        case 1:
            allInput = '#formFilesInputAll';
            fileInput = '.form_files_input';
            break;
        case 2:
            allInput = '#commonFilesInputAll';
            fileInput = '.common_files_input';
            break;
        case 3:
            allInput = '#mainFilesInputAll';
            fileInput = '.main_files_input';
            break;
    }
    // 全选
    if (allType === 0) {
        var checkedOfAll = $(allInput).prop("checked");
        $(fileInput).prop("checked", checkedOfAll);
    } else if (allType === 1) { // 单选
        var $this = $(this);
        if ($this.checked == false) {
            $(allInput).prop('checked', false);
        } else {
            var count = $(fileInput + ":checkbox:checked").length;
            if (count == $(fileInput).length) {
                $(allInput).prop("checked", true);
            } else {
                $(allInput).prop("checked", false);
            }
        }
    }
}

// 文件批量下载
$.dynamicSubmit = function (url, datas, fn) {
    var form = $('#dynamicForm');
    if (form.length <= 0) {
        form = $("<form>");
        form.attr('id', 'dynamicForm');
        form.attr('style', 'display:none');
        form.attr('target', '');
        form.attr('method', 'post');
        $('body').append(form);
    }
    form = $('#dynamicForm');
    form.attr('action', url);
    form.empty();
    if (datas && typeof (datas) == 'object') {
        for (var item in datas) {
            var $_input = $('<input>');
            $_input.attr('type', 'hidden');
            $_input.attr('name', item);
            $_input.val(datas[item]);
            $_input.appendTo(form);
        }
    }
    form.submit();
    // form.remove();
    if (fn) {
        fn();
    }
};

// 保存表单会签
function saveFormSign(loadingIndex, fn) {
    var flowfun = globalData.flowRun;
    var form_item = $('.special_form_item');
    var sign = $('.sign');
    if (globalData.feedback == '2') {  //如果值为2，判断强制会签
        var flowstep = globalData.flowPrcs
        var arr = [];
        var userId = $.cookie('userId');
        if (globalData.data != "" && globalData.data != undefined) {
            globalData.data.forEach(function (v, i) {
                arr.push(v.userId)
            })
            if (arr.indexOf(userId) < 0) {
                $.layerMsg({content: '请提交会签意见', icon: 6});
                return false;
            }
        } else {
            $.layerMsg({content: '请提交会签意见', icon: 6});
            return false;
        }

    }
    //处理会签控件
    if (sign.length != 0) {
        var signdata = [];
        for (var i = 0; i < sign.length; i++) {
            if (!sign.eq(i).attr('disabled')) {
                var obj = sign.eq(i);
                var pre = obj.prev();
                var realValue = obj.val().trim();
                var baseData = {};
                var value = '';
                var ismust = obj.attr('ismust');
                var isMustValue = '';
                if (realValue) {
                    var $eiderarea = pre.find('.eiderarea').eq(pre.find('.eiderarea').length - 1);
                    if (!$eiderarea.attr('time_stamp')) {
                        var timeStamp = new Date().getTime();
                        $eiderarea.attr('time_stamp', timeStamp);
                    }

                    value = Mustache.render($eiderarea.prop("outerHTML"), {content: ''});
                    isMustValue = value;
                } else {
                    var pre = obj.prev();
                    var $eiderarea = pre.find('.eiderarea');
                    var flowRunPrcs = workForm.option.flowRunPrcs;
                    $eiderarea.each(function (index, ele) {
                        if ($(this).attr('user_id') == flowRunPrcs.userId && $(this).attr('prcs_id') == flowRunPrcs.flowPrcs) {
                            var signHtml = $(ele).prop("outerHTML");
                            var contentArr = signHtml.split(/>/);
                            var content = contentArr[1].split(/</)[0];
                            if (content.indexOf('{{content}}') == -1 && content.trim() != '') {
                                isMustValue += content
                            }
                        }
                    });
                }

                if (ismust == 'true' && isMustValue == "") {
                    layer.close(loadingIndex);
                    $.layerMsg({content: '请填写' + obj.attr('title'), icon: 1});
                    return false;
                }

                baseData["key"] = sign.eq(i).attr('name');
                baseData["value"] = value;
                signdata.push(baseData);
            }
        }
        if (signdata.length != 0) {
            $.ajax({
                type: "post",
                url: "/workflow/work/signControl",
                dataType: 'JSON',
                data: {
                    runId: flowfun.runId,
                    flowId: flowId,
                    signdata: JSON.stringify(signdata)
                },
                async: false,
                success: function (res) {
                    $('.sign').val('');
                }
            });
        }
    }
    /********传阅会签控件开始**********/
    if (form_item.length != 0) {
        for (var i = 0; i < form_item.length; i++) {
            var obj = form_item.eq(i);
            var ismust = obj.attr('ismust');
            if (ismust == 'true' && $('.countersignature_itemhide').length == 0) {          //适用于设置了当前流程必填字段和当前流程转出条件的流程
                layer.msg('请签名!', {icon: 1});
                return false;
            } else {
                saveCSNtr_item(obj, function () {
                    if (fn) {
                        fn();
                    }
                });
                return false;
            }
        }
    } else {
        if (fn) {
            fn();
        }
    }
}